<template>
  <div class="admin-statistics">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">数据统计</h1>
        <p class="page-subtitle">系统运营数据分析与统计报告</p>
      </div>
      <div class="header-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="loadAllData"
        />
        <el-button type="primary" @click="exportReport">
          <el-icon><Download /></el-icon>
          导出报告
        </el-button>
      </div>
    </div>

    <!-- 概览统计 -->
    <el-row :gutter="20" class="overview-row">
      <el-col :xs="12" :sm="6">
        <el-card class="overview-card">
          <div class="overview-content">
            <div class="overview-info">
              <div class="overview-number">{{ overview.totalUsers }}</div>
              <div class="overview-label">总用户数</div>
              <div class="overview-trend" :class="overview.usersTrend > 0 ? 'positive' : 'negative'">
                <el-icon><CaretTop v-if="overview.usersTrend > 0" /><CaretBottom v-else /></el-icon>
                {{ Math.abs(overview.usersTrend) }}%
              </div>
            </div>
            <el-icon class="overview-icon"><User /></el-icon>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6">
        <el-card class="overview-card">
          <div class="overview-content">
            <div class="overview-info">
              <div class="overview-number">{{ overview.totalActivities }}</div>
              <div class="overview-label">总活动数</div>
              <div class="overview-trend" :class="overview.activitiesTrend > 0 ? 'positive' : 'negative'">
                <el-icon><CaretTop v-if="overview.activitiesTrend > 0" /><CaretBottom v-else /></el-icon>
                {{ Math.abs(overview.activitiesTrend) }}%
              </div>
            </div>
            <el-icon class="overview-icon"><Calendar /></el-icon>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6">
        <el-card class="overview-card">
          <div class="overview-content">
            <div class="overview-info">
              <div class="overview-number">{{ overview.totalRegistrations }}</div>
              <div class="overview-label">总报名数</div>
              <div class="overview-trend" :class="overview.registrationsTrend > 0 ? 'positive' : 'negative'">
                <el-icon><CaretTop v-if="overview.registrationsTrend > 0" /><CaretBottom v-else /></el-icon>
                {{ Math.abs(overview.registrationsTrend) }}%
              </div>
            </div>
            <el-icon class="overview-icon"><Tickets /></el-icon>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6">
        <el-card class="overview-card">
          <div class="overview-content">
            <div class="overview-info">
              <div class="overview-number">{{ overview.avgRating.toFixed(1) }}</div>
              <div class="overview-label">平均评分</div>
              <div class="overview-trend" :class="overview.ratingTrend > 0 ? 'positive' : 'negative'">
                <el-icon><CaretTop v-if="overview.ratingTrend > 0" /><CaretBottom v-else /></el-icon>
                {{ Math.abs(overview.ratingTrend).toFixed(1) }}
              </div>
            </div>
            <el-icon class="overview-icon"><Star /></el-icon>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20">
      <!-- 用户增长趋势 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>用户增长趋势</span>
              <el-radio-group v-model="userChartType" size="small" @change="loadUserTrend">
                <el-radio-button label="daily">日</el-radio-button>
                <el-radio-button label="weekly">周</el-radio-button>
                <el-radio-button label="monthly">月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          
          <div ref="userTrendChart" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <!-- 活动统计 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <span>活动统计</span>
          </template>
          
          <div ref="activityChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <!-- 活动类型分布 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <span>活动类型分布</span>
          </template>
          
          <div ref="activityTypeChart" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <!-- 报名状态分布 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <span>报名状态分布</span>
          </template>
          
          <div ref="registrationStatusChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <!-- 热门活动排行 -->
      <el-col :xs="24" :lg="12">
        <el-card class="table-card">
          <template #header>
            <span>热门活动排行</span>
          </template>
          
          <el-table :data="popularActivities" stripe>
            <el-table-column type="index" label="排名" width="60" />
            <el-table-column prop="title" label="活动名称" show-overflow-tooltip />
            <el-table-column prop="organizerName" label="组织者" width="100" />
            <el-table-column prop="registrationCount" label="报名数" width="80" />
            <el-table-column prop="rating" label="评分" width="80">
              <template #default="{ row }">
                {{ row.rating ? row.rating.toFixed(1) : '-' }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      
      <!-- 活跃用户排行 -->
      <el-col :xs="24" :lg="12">
        <el-card class="table-card">
          <template #header>
            <span>活跃用户排行</span>
          </template>
          
          <el-table :data="activeUsers" stripe>
            <el-table-column type="index" label="排名" width="60" />
            <el-table-column label="用户" width="120">
              <template #default="{ row }">
                <div class="user-info">
                  <el-avatar :src="row.avatar" :size="24">
                    {{ row.realName?.charAt(0) || row.username?.charAt(0) }}
                  </el-avatar>
                  <span class="user-name">{{ row.realName || row.username }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="role" label="角色" width="80">
              <template #default="{ row }">
                <el-tag :type="getRoleType(row.role)" size="small">
                  {{ getRoleText(row.role) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="activityCount" label="参与活动" width="80" />
            <el-table-column prop="lastActiveAt" label="最后活跃" width="100">
              <template #default="{ row }">
                {{ formatDate(row.lastActiveAt, 'MM-DD') }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 系统使用统计 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :xs="24">
        <el-card class="usage-card">
          <template #header>
            <span>系统使用统计</span>
          </template>
          
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="6">
              <div class="usage-item">
                <div class="usage-title">今日访问量</div>
                <div class="usage-value">{{ usageStats.todayVisits }}</div>
                <div class="usage-compare">
                  较昨日 
                  <span :class="usageStats.visitsChange > 0 ? 'positive' : 'negative'">
                    {{ usageStats.visitsChange > 0 ? '+' : '' }}{{ usageStats.visitsChange }}%
                  </span>
                </div>
              </div>
            </el-col>
            
            <el-col :xs="24" :sm="12" :md="6">
              <div class="usage-item">
                <div class="usage-title">今日新增用户</div>
                <div class="usage-value">{{ usageStats.todayNewUsers }}</div>
                <div class="usage-compare">
                  较昨日 
                  <span :class="usageStats.newUsersChange > 0 ? 'positive' : 'negative'">
                    {{ usageStats.newUsersChange > 0 ? '+' : '' }}{{ usageStats.newUsersChange }}%
                  </span>
                </div>
              </div>
            </el-col>
            
            <el-col :xs="24" :sm="12" :md="6">
              <div class="usage-item">
                <div class="usage-title">今日新增活动</div>
                <div class="usage-value">{{ usageStats.todayNewActivities }}</div>
                <div class="usage-compare">
                  较昨日 
                  <span :class="usageStats.newActivitiesChange > 0 ? 'positive' : 'negative'">
                    {{ usageStats.newActivitiesChange > 0 ? '+' : '' }}{{ usageStats.newActivitiesChange }}%
                  </span>
                </div>
              </div>
            </el-col>
            
            <el-col :xs="24" :sm="12" :md="6">
              <div class="usage-item">
                <div class="usage-title">今日新增报名</div>
                <div class="usage-value">{{ usageStats.todayNewRegistrations }}</div>
                <div class="usage-compare">
                  较昨日 
                  <span :class="usageStats.newRegistrationsChange > 0 ? 'positive' : 'negative'">
                    {{ usageStats.newRegistrationsChange > 0 ? '+' : '' }}{{ usageStats.newRegistrationsChange }}%
                  </span>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { formatDate } from '@/utils'
import { ElMessage } from 'element-plus'
import api from '@/utils/api'
import * as echarts from 'echarts'
import {
  Download,
  CaretTop,
  CaretBottom,
  User,
  Calendar,
  Tickets,
  Star
} from '@element-plus/icons-vue'

const dateRange = ref([
  formatDate(new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), 'YYYY-MM-DD'),
  formatDate(new Date(), 'YYYY-MM-DD')
])

const userChartType = ref('daily')

const userTrendChart = ref()
const activityChart = ref()
const activityTypeChart = ref()
const registrationStatusChart = ref()

let userTrendChartInstance = null
let activityChartInstance = null
let activityTypeChartInstance = null
let registrationStatusChartInstance = null

const overview = reactive({
  totalUsers: 0,
  usersTrend: 0,
  totalActivities: 0,
  activitiesTrend: 0,
  totalRegistrations: 0,
  registrationsTrend: 0,
  avgRating: 0,
  ratingTrend: 0
})

const popularActivities = ref([])
const activeUsers = ref([])

const usageStats = reactive({
  todayVisits: 0,
  visitsChange: 0,
  todayNewUsers: 0,
  newUsersChange: 0,
  todayNewActivities: 0,
  newActivitiesChange: 0,
  todayNewRegistrations: 0,
  newRegistrationsChange: 0
})

const getRoleType = (role) => {
  const typeMap = {
    student: 'primary',
    organizer: 'success',
    admin: 'danger'
  }
  return typeMap[role] || ''
}

const getRoleText = (role) => {
  const textMap = {
    student: '学生',
    organizer: '组织者',
    admin: '管理员'
  }
  return textMap[role] || role
}

const loadOverview = async () => {
  try {
    const params = {
      startDate: dateRange.value[0],
      endDate: dateRange.value[1]
    }
    
    const response = await api.get('/admin/statistics/overview', { params })
    const data = response.data.data
    
    Object.assign(overview, data)
    
  } catch (error) {
    console.error('加载概览数据失败:', error)
  }
}

const loadUserTrend = async () => {
  try {
    const params = {
      startDate: dateRange.value[0],
      endDate: dateRange.value[1],
      type: userChartType.value
    }
    
    const response = await api.get('/admin/statistics/user-trend', { params })
    const data = response.data.data
    
    renderUserTrendChart(data)
    
  } catch (error) {
    console.error('加载用户趋势数据失败:', error)
  }
}

const loadActivityStats = async () => {
  try {
    const params = {
      startDate: dateRange.value[0],
      endDate: dateRange.value[1]
    }
    
    const response = await api.get('/admin/statistics/activity-stats', { params })
    const data = response.data.data
    
    renderActivityChart(data.trend)
    renderActivityTypeChart(data.typeDistribution)
    
  } catch (error) {
    console.error('加载活动统计数据失败:', error)
  }
}

const loadRegistrationStats = async () => {
  try {
    const params = {
      startDate: dateRange.value[0],
      endDate: dateRange.value[1]
    }
    
    const response = await api.get('/admin/statistics/registration-stats', { params })
    const data = response.data.data
    
    renderRegistrationStatusChart(data.statusDistribution)
    
  } catch (error) {
    console.error('加载报名统计数据失败:', error)
  }
}

const loadPopularActivities = async () => {
  try {
    const params = {
      startDate: dateRange.value[0],
      endDate: dateRange.value[1],
      limit: 10
    }
    
    const response = await api.get('/admin/statistics/popular-activities', { params })
    popularActivities.value = response.data.data || []
    
  } catch (error) {
    console.error('加载热门活动数据失败:', error)
  }
}

const loadActiveUsers = async () => {
  try {
    const params = {
      startDate: dateRange.value[0],
      endDate: dateRange.value[1],
      limit: 10
    }
    
    const response = await api.get('/admin/statistics/active-users', { params })
    activeUsers.value = response.data.data || []
    
  } catch (error) {
    console.error('加载活跃用户数据失败:', error)
  }
}

const loadUsageStats = async () => {
  try {
    const response = await api.get('/admin/statistics/usage-stats')
    const data = response.data.data
    
    Object.assign(usageStats, data)
    
  } catch (error) {
    console.error('加载使用统计数据失败:', error)
  }
}

const renderUserTrendChart = (data) => {
  if (!userTrendChartInstance) {
    userTrendChartInstance = echarts.init(userTrendChart.value)
  }
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['新增用户', '累计用户']
    },
    xAxis: {
      type: 'category',
      data: data.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '新增用户',
        type: 'bar',
        data: data.newUsers,
        itemStyle: {
          color: '#409eff'
        }
      },
      {
        name: '累计用户',
        type: 'line',
        data: data.totalUsers,
        itemStyle: {
          color: '#67c23a'
        }
      }
    ]
  }
  
  userTrendChartInstance.setOption(option)
}

const renderActivityChart = (data) => {
  if (!activityChartInstance) {
    activityChartInstance = echarts.init(activityChart.value)
  }
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['新增活动', '活动报名']
    },
    xAxis: {
      type: 'category',
      data: data.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '新增活动',
        type: 'bar',
        data: data.newActivities,
        itemStyle: {
          color: '#e6a23c'
        }
      },
      {
        name: '活动报名',
        type: 'line',
        data: data.registrations,
        itemStyle: {
          color: '#f56c6c'
        }
      }
    ]
  }
  
  activityChartInstance.setOption(option)
}

const renderActivityTypeChart = (data) => {
  if (!activityTypeChartInstance) {
    activityTypeChartInstance = echarts.init(activityTypeChart.value)
  }
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  activityTypeChartInstance.setOption(option)
}

const renderRegistrationStatusChart = (data) => {
  if (!registrationStatusChartInstance) {
    registrationStatusChartInstance = echarts.init(registrationStatusChart.value)
  }
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  registrationStatusChartInstance.setOption(option)
}

const loadAllData = async () => {
  await Promise.all([
    loadOverview(),
    loadUserTrend(),
    loadActivityStats(),
    loadRegistrationStats(),
    loadPopularActivities(),
    loadActiveUsers(),
    loadUsageStats()
  ])
}

const exportReport = async () => {
  try {
    const response = await api.get('/admin/statistics/export', {
      params: {
        startDate: dateRange.value[0],
        endDate: dateRange.value[1]
      },
      responseType: 'blob'
    })
    
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `统计报告_${dateRange.value[0]}_${dateRange.value[1]}.xlsx`
    link.click()
    
    window.URL.revokeObjectURL(url)
    ElMessage.success('报告导出成功')
    
  } catch (error) {
    ElMessage.error('导出报告失败')
  }
}

const resizeCharts = () => {
  nextTick(() => {
    userTrendChartInstance?.resize()
    activityChartInstance?.resize()
    activityTypeChartInstance?.resize()
    registrationStatusChartInstance?.resize()
  })
}

onMounted(async () => {
  await nextTick()
  await loadAllData()
  
  // 监听窗口大小变化
  window.addEventListener('resize', resizeCharts)
})
</script>

<style scoped>
.admin-statistics {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
}

.header-content {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  opacity: 0.9;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
  margin-left: 20px;
  align-items: center;
}

.overview-row {
  margin-bottom: 24px;
}

.overview-card {
  cursor: pointer;
  transition: transform 0.3s ease;
}

.overview-card:hover {
  transform: translateY(-2px);
}

.overview-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.overview-info {
  flex: 1;
}

.overview-number {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
}

.overview-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.overview-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 600;
}

.overview-trend.positive {
  color: #67c23a;
}

.overview-trend.negative {
  color: #f56c6c;
}

.overview-icon {
  font-size: 32px;
  opacity: 0.3;
  color: #409eff;
}

.chart-card,
.table-card,
.usage-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-name {
  font-size: 13px;
  color: #303133;
}

.usage-item {
  text-align: center;
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background: #fafafa;
}

.usage-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.usage-value {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
}

.usage-compare {
  font-size: 12px;
  color: #606266;
}

.usage-compare .positive {
  color: #67c23a;
}

.usage-compare .negative {
  color: #f56c6c;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .header-actions {
    margin-left: 0;
    flex-direction: column;
  }
  
  .overview-card {
    margin-bottom: 16px;
  }
  
  .chart-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .usage-item {
    margin-bottom: 16px;
  }
}
</style>